package __web

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"io"
	"log"
	"os"
	"time"
)

// MyMiddleware 中间件
func MyMiddleware(c *gin.Context) {
	log.Println("前置中间件")
	// 可以做数据传递，在控制器中获取数据
	c.Set("time", "anything")
	// next 之前的代码是前置中间件
	c.Next()
	// next 之后的代码是后置中间件
	log.Println("后置中间件")
}

func GinDemo() {
	// 设置日志
	// 框架的日志只是记录用户请求，自己的日志可能需要用到第三方框架保存
	// Disable Console Color, you don't need console color when writing the logs to file.
	// gin.DisableConsoleColor()
	// Logging to a file.
	f, _ := os.Create("gin.log")
	// gin.DefaultWriter = io.MultiWriter(f)

	// Use the following code if you need to write the logs to file and console at the same time.
	gin.DefaultWriter = io.MultiWriter(f, os.Stdout)

	// 默认添加了两个中间件
	// Logger 和 Recovery
	router := gin.Default()
	// 全局中间件
	router.Use(MyMiddleware)

	// 如果不想用默认的，可以设置自己的中间件
	// router := gin.New()
	// router.Use(gin.Logger(), gin.Recovery())

	// Simple group: v1
	// 同样也可以在分组中使用中间件
	v1 := router.Group("/v1")

	// This handler will match /user/john but will not match /user/ or /user
	// 使用了对单个路由的中间件
	// v1.GET("/user/:name", MyMiddleware, controller.GetUserName)
	v1.GET("/user/:name", GetUserName)

	// However, this one will match /user/john/ and also /user/john/send
	// If no other routers match /user/john, it will redirect to /user/john/
	v1.GET("/user/:name/*action", GetUserAction)

	// For each matched request Context will hold the route definition
	v1.POST("/user/:name/*action", PostUserAction)

	// This handler will add a new router for /user/groups.
	// Exact routes are resolved before param routes, regardless of the order they were defined.
	// Routes starting with /user/groups are never interpreted as /user/:name/... routes
	v1.GET("/user/groups", GetUserGroup)

	// 上传图片
	v1.POST("/user/image", UploadImage)

	// 登录
	v1.POST("/user/login", BindJson)

	router.Run(":8080")

}

// CustomLogFormat 自定义日志
// 一般来说用
func CustomLogFormat() {
	router := gin.New()

	// LoggerWithFormatter middleware will write the logs to gin.DefaultWriter
	// By default gin.DefaultWriter = os.Stdout
	router.Use(gin.LoggerWithFormatter(func(param gin.LogFormatterParams) string {

		// your custom format
		return fmt.Sprintf("%s - [%s] \"%s %s %s %d %s \"%s\" %s\"\n",
			param.ClientIP,
			param.TimeStamp.Format(time.RFC1123),
			param.Method,
			param.Path,
			param.Request.Proto,
			param.StatusCode,
			param.Latency,
			param.Request.UserAgent(),
			param.ErrorMessage,
		)
	}))
}
